# data_loader.py
import pandas as pd
import numpy as np
from typing import List
from vrp_model import Customer, VRPTWInstance, Vehicle


def convert_time(time_obj):
    """将Excel时间对象转换为分钟数"""
    if isinstance(time_obj, str):
        # 处理字符串格式的小时数
        return int(float(time_obj) * 60)
    elif isinstance(time_obj, (float, int)):
        return int(time_obj * 60)
    else:  # 处理datetime.time对象
        return time_obj.hour * 60 + time_obj.minute

def load_data() -> VRPTWInstance:
    # 加载位置数据
    loc_df = pd.read_excel('F:\\essays\\data\\location.xlsx')
    customers = []
    for _, row in loc_df.iterrows():
        customers.append(Customer(
            id=int(row['序号']),
            x=row['经度'],
            y=row['纬度'],
            demand=0,
            volume=0,
            early=0,
            late=1440
        ))

    # 加载约束数据
    constraint_df = pd.read_excel('F:\\essays\\data\\yueshu.xlsx')
    for _, row in constraint_df.iterrows():
        if row['序号'] == 0:
            continue

        # 转换时间格式
        early = convert_time(row['最早服务时间'])
        late = convert_time(row['最晚服务时间'])

        customers[row['序号']].demand = row['需求量(kg)']
        customers[row['序号']].volume = row['体积']
        customers[row['序号']].early = early
        customers[row['序号']].late = late

    # 加载距离和时间数据
    dist_time_df = pd.read_excel('F:\\essays\\data\\distanceandtime.xlsx')
    size = len(customers)
    distance_matrix = np.zeros((size, size))
    time_matrix = np.zeros((size, size))

    for _, row in dist_time_df.iterrows():
        i = int(row['start'])
        j = int(row['end'])
        distance_matrix[i][j] = row['distance(km)']
        time_matrix[i][j] = row['time(min)']
        # 假设对称路径
        distance_matrix[j][i] = row['distance(km)']
        time_matrix[j][i] = row['time(min)']

    vehicle = Vehicle(
        capacity=2000,
        volume=12.76,
        max_range=200
    )

    return VRPTWInstance(
        customers=customers,
        depot=customers[0],
        distance_matrix=distance_matrix,
        time_matrix=time_matrix,
        vehicle=vehicle
    )